package com.traffic.between.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import net.sf.json.JSONObject;

public class Xml2JsonUtil {
	/**
	 * 转换一个xml格式的字符串到json格式
	 * 
	 * @param xml
	 *            xml格式的字符串
	 * @return 成功返回json 格式的字符串;失败反回null
	 */
	public static String xml2JSON(String xml) {
		JSONObject obj = new JSONObject();
		try {
			InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
			SAXBuilder sb = new SAXBuilder();
			Document doc = sb.build(is);
			Element root = doc.getRootElement();
			obj.put(root.getName(), iterateElement(root));
			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 转换一个xml格式的字符串到json格式
	 * 
	 * @param file
	 *            java.io.File实例是一个有效的xml文件
	 * @return 成功反回json 格式的字符串;失败反回null
	 */
	public static String xml2JSON(File file) {
		JSONObject obj = new JSONObject();
		try {
			SAXBuilder sb = new SAXBuilder();
			Document doc = sb.build(file);
			Element root = doc.getRootElement();
			obj.put(root.getName(), iterateElement(root));
			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 一个迭代方法
	 * 
	 * @param element
	 *            : org.jdom.Element
	 * @return java.util.String 实例
	 */
	@SuppressWarnings("unchecked")
	private static Map<String, Object> iterateElement(Element element) {
		List<Object> jiedian = element.getChildren();
		Element et = null;
		Map<String, Object> obj = new HashMap<String, Object>();
		for (int i = 0; i < jiedian.size(); i++) {
			et = (Element) jiedian.get(i);
			if ("".equals(et.getTextTrim())) {
				if (et.getChildren().size() == 0)
					continue;
				obj.put(et.getName(), iterateElement(et));
			} else {
				obj.put(et.getName(), et.getTextTrim());
			}
		}
		return obj;
	}

	@SuppressWarnings("unchecked")
	public static String xmlToJson(String protocolXML) {
		JSONObject obj = new JSONObject();
		StringReader reader = new StringReader(protocolXML);
		InputSource source = new InputSource(reader);
		SAXBuilder saxBuilder = new SAXBuilder();

		try {
			Document doc = saxBuilder.build(source);
			Element root = doc.getRootElement();
			List<Element> list = root.getChildren();

			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					Element element = (Element) list.get(i);
					obj.put(element.getName(), element.getValue());
				}
			} else {
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return obj.toString();
	}

	public static String requestBodyXmlToJson(String xml) {
		JSONObject obj = new JSONObject();
		StringReader reader = new StringReader(xml);
		InputSource source = new InputSource(reader);
		SAXBuilder saxBuilder = new SAXBuilder();
		try {
			Document doc = saxBuilder.build(source);
			Element root = doc.getRootElement();
			Element body = root.getChild("body");
			Element item = body.getChild("item");
			List<Element> list = item.getChildren();
			if (null !=list) {
				for (Element element : list) {
					obj.put(element.getName(), element.getValue());
				}
			}
			else {
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return obj.toString();
	}
	public static String requestHeadXmlToJson(String xml) {
		JSONObject obj = new JSONObject();
		StringReader reader = new StringReader(xml);
		InputSource source = new InputSource(reader);
		SAXBuilder saxBuilder = new SAXBuilder();
		try {
			Document doc = saxBuilder.build(source);
			Element root = doc.getRootElement();
			Element head = root.getChild("head");
			List<Element> list = head.getChildren();
			if (null !=list) {
				for (Element element : list) {
					obj.put(element.getName(), element.getValue());
				}
			}
			else {
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return obj.toString();
	}
	// 测试
	public static void main(String[] args) throws JDOMException, IOException {
		// System.out.println( Xml2JsonUtil.xml2JSON("<MapSet>"
		// + "<MapGroup id='Sheboygan'>" + "<Map>"
		// + "<Type>MapGuideddddddd</Type>"
		// + "<SingleTile>true</SingleTile>" + "<Extension>"
		// + "<ResourceId>ddd</ResourceId>" + "</Extension>" + "</Map>"
		// + "<Map>" + "<Type>ccc</Type>" + "<SingleTile>ggg</SingleTile>"
		// + "<Extension>" + "<ResourceId>aaa</ResourceId>"
		// + "</Extension>" + "</Map>" + "<Extension />" + "</MapGroup>"
		// + "<ddd>" + "33333333" + "</ddd>" + "<ddd>" + "444" + "</ddd>"
		// + "</MapSet>"));

		// System.out.println(Xml2JsonUtil.xml2JSON(
		// "<response><tbOrderNo>哈哈哈</tbOrderNo><coopOrderStatus>xxx</coopOrderStatus><coopOrderNo>xxx</coopOrderNo><errorCode>xxx</errorCode><errorDesc>xxx</errorDesc></response>"));

		// String text
		// ="<XML><A>123</A><B>whl123</B><C>亮亮</C><D>1</D><E>1</E><F>165074</F><G>贫穷</G><H>1698.0</H><I>初级士官</I><J>湖南</J><K>常德</K><L>1</L></XML>";
		//

		String xml = "<request>"
				+ "<head><custInteId>100</custInteId><echo>200</echo><timestamp>100</timestamp><chargeSign>22</chargeSign>"
				+ "</head>"
				+ "<body>"
				+ "<item><orderId>100</orderId><orderType>222</orderType><packCode></packCode><mobile></mobile><result>0000</result><desc></desc><gateErrorCode></gateErrorCode>"
				+ "</item>"
				+ "<item><orderId>200</orderId><orderType>222</orderType><packCode></packCode><mobile></mobile><result>1001</result><desc></desc><gateErrorCode></gateErrorCode>"
				+ "</item>" + "</body>" + "</request>";
		// System.out.println(xml2JSON(xml));
		StringReader reader = new StringReader(xml);
		InputSource source = new InputSource(reader);
		SAXBuilder saxBuilder = new SAXBuilder();

		Document doc = saxBuilder.build(source);
		Element root = doc.getRootElement();

		Element body = root.getChild("body");
		List<Element> list = body.getChildren();
		Map<String,Object> map = new HashMap<String,Object>();
		List<Map<String,Object>> listData = new ArrayList<Map<String,Object>>();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Element element = (Element) list.get(i);
				List<Element> children = element.getChildren();
				for (Element child : children) {
					map.put(child.getName(),child.getValue());
					listData.add(map);
				}

			}
		}
	   System.out.println(listData.get(0));
		System.out.println(listData.get(0).get("desc").toString());

	}

}